package com.zeyi.chat.handler;

import com.zeyi.chat.annotation.Mapping;
import com.zeyi.chat.dto.Message;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * @author zeyi
 */
public class Dispatcher extends Thread {
    private Socket socket;

    public Dispatcher(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) ois.readObject();
                String[] split = message.getHandlePath().split("/");
                Class<?> aClass = Class.forName("com.zeyi.chat.handler." + split[0]);
                try {
                    Method init = aClass.getMethod("getInstance");
                    Method[] methods = aClass.getMethods();
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(Mapping.class)) {
                            Mapping mapping = method.getAnnotation(Mapping.class);
                            if (mapping.value().equals(split[1])) {
                                method.invoke(init.invoke(null), message);
                                break;
                            }
                        }
                    }
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
